<?php

namespace App\Http\Controllers\Api;

use App\Models\User;
use Dingo\Api\Http\Request;

class AuthController extends BaseController
{
    public function login(Request $request)
    {
        $input = $request->input();
        \Log::info("weixin-login-param : " . var_export($input, true));
        $this->validate($request, [
            'code' => 'required',
            'encryptedData' => 'required',
            'iv' => 'required',
        ]);
        $app = $this->miniProgram();

        $session = $app->auth->session($request->code);
        \Log::info("weixin-session : " . var_export($session, true));
        if (isset($session['errcode']) &&  $session['errcode'] > 0)
            return $this->failed($session['errmsg']);

//        $session['session_key'] = 'm92yQvG87nZhZM2go7QtOQ==';
        try {
            $userInfo = $app->encryptor->decryptData(
                $session['session_key'],
                $request->iv,
                $request->encryptedData
            );
            \Log::info("weixin-decrypt : " . var_export($userInfo, true));
        } catch (\Exception $e) {
            \Log::error($e->getMessage());
            return $this->failed('网络异常，请重新操作');
        }

        $user = User::where('weixin_openid', $userInfo['openId'])->dontRemember()->first();
        if (!$user) {
            $user = new User();
            $user->weixin_openid = $userInfo['openId'];
            $user->weixin_union_id = $userInfo['unionId'] ?? null;
            $user->session_key = $session['session_key'];
            $user->nickname = $userInfo['nickName'];
            $user->gender = $userInfo['gender'];
            $user->language = $userInfo['language'];
            $user->city = $userInfo['city'];
            $user->province = $userInfo['province'];
            $user->country = $userInfo['country'];
            $user->avatar_url = $userInfo['avatarUrl'];
            $user->save();
        } else {
            $user->session_key = $session['session_key'];
            $user->save();
            User::deleteCachePk($user->id);
        }

        if (!$token = \Auth::guard('api')->fromUser($user)) {
            return $this->failed('登录失败', 401);
        }

        return $this->respondWithToken($token);
    }




}